/**
 * 
 */
package mocku.agent;

import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.util.Properties;
import mocku.transformer.ProxyTransformer;


/**
 * MockU Instrumentation Agent. 
 * Loads properties from mocku.properties.
 * Properties must be configured like a properties file indicating:
 * class_to_mock=mock_implementation
 *
 * @author aambertin
 */
public class MockUAgent {

	private static Instrumentation __instrumentation;
	
	/**
	 * method call by jvm agent manager.
	 * @param arguments
	 * @param instrumentation
	 */
	public static void premain (String arguments, Instrumentation instrumentation) {
		__instrumentation = instrumentation;
		Properties config = loadConfig();
		instrumentation.addTransformer(new ProxyTransformer(config));
	}
	
	
	/**
	 * Load properties from mocku.properties
	 * @return
	 */
	private static Properties loadConfig() {
		ClassLoader loader = MockUAgent.class.getClassLoader();
		Properties config = new Properties();
		try {
			InputStream stream = loader.getResourceAsStream("mocku.properties");
			config.load(stream);
			System.out.println("MockU Properties: "+config);
			return config;
		}
		catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException("Failed to load mocku.properties",e);
		}
	}


	/**
	 * Return the instrumentation instance.
	 * @return Instrumentation
	 */
	public Instrumentation getInstrumentation() {
		return __instrumentation;
	}
}
